﻿using Gl_mes.BLL.Mes;
using MesBSW.BLL.Mes;
using MesBSW.DAL.MesDB;
using MesBSW.Tools;
using MesBSW.View.Dialog.Mes.Materail;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MesBSW.View.PMC
{
    public partial class InputMaterialFrm : UIPage 
    {
        public InputMaterialFrm()
        {
            InitializeComponent();
        }

        #region "内部变量"
        private KingdeeControler _king_ctrl = new KingdeeControler();
        private MaterialControler _mat_ctrl = new MaterialControler();
        private List<MatGroup> _group_list = new List<MatGroup>();

        private decimal _tmp_board_qty = 0;
        #endregion


        #region "控件事件"
        /// <summary>
        /// 界面加载时，初始化分类树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void InputMaterialFrm_Load(object sender, EventArgs e)
        {
            this.InitMaterialGroupTreeView();

            LanguageTools.ChangeControlTextForLangType(this, MainFrm.CurrLanguage);
        }


        /// <summary>
        /// 加载金蝶新建的物料
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLoadMaterial_Click(object sender, EventArgs e)
        {
            CopyMaterialDia tmpDia = new CopyMaterialDia();
            tmpDia.ShowDialog();
        }

        /// <summary>
        /// 查询物料信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            MatGroup groupBean = null;
            int tmpInt = 0;
            if (this.tvwGroup.SelectedNode != null && this.tvwGroup.SelectedNode.Tag != null && int.TryParse(this.tvwGroup.SelectedNode.Tag.ToString(), out tmpInt))
            {
                var query = this._group_list.Where(q => q.group_id == tmpInt);
                groupBean = query != null && query.Count() > 0 ? query.First<MatGroup>() : null;
            }

            if (groupBean != null && groupBean.group_id > 0)
            {
                List<MatInfo> tmpList = this._mat_ctrl.SearchMatInfoForCondition(groupBean, this.txtMatNumber.Text.Trim(),
                                                                                        this.txtMatName.Text.Trim(), this.txtMatSpe.Text.Trim());
                DataTable tmpDt = this.ChangeMatInfoListToDataTable(tmpList);
                tmpDt.AcceptChanges();
                this.dgvMaterial.DataSource = tmpDt;
                
                if (tmpList is null || tmpList.Count <= 0)
                {
                    UIMessageBox.ShowWarning("没有找到符合条件的物料存在！");
                }
            }
            else
            {
                UIMessageBox.ShowWarning("请选择物料分类后再作查询操作！");
            }
        }
        #endregion


        #region "内部方法"
        /// <summary>
        /// 加载物料分类，产生分类树
        /// </summary>
        private void InitMaterialGroupTreeView()
        {
            this._group_list = this._mat_ctrl.SearchAllMatGroups();
            TreeNode groupNode = this._mat_ctrl.InitMaterialGroupTreeNode(this._group_list);
            this.tvwGroup.Nodes.Add(groupNode);
        }

        /// <summary>
        /// 将物料信息由实体类转化成DataTable
        /// </summary>
        /// <param name="matList"></param>
        /// <returns></returns>
        private DataTable ChangeMatInfoListToDataTable(List<MatInfo> matList)
        {
            DataTable resDt = new DataTable();
            resDt.Columns.Add("index", typeof(int));
            resDt.Columns.Add("mat_id", typeof(int));
            resDt.Columns.Add("mat_number", typeof(string));
            resDt.Columns.Add("mat_name", typeof(string));
            resDt.Columns.Add("mat_spe", typeof(string));
            resDt.Columns.Add("base_unit", typeof(string));
            resDt.Columns.Add("create_orgid", typeof(string));
            resDt.Columns.Add("use_orgid", typeof(string));
            resDt.Columns.Add("mat_group", typeof(int));
            resDt.Columns.Add("doc_status", typeof(string));
            resDt.Columns.Add("forbid_status", typeof(string));
            resDt.Columns.Add("board_qty", typeof(decimal));
            resDt.Columns.Add("data_status", typeof(string));

            if (matList != null && matList.Count > 0)
            {
                int index = 0;
                foreach (var matBean in matList.OrderBy(q => q.mat_number))
                {
                    DataRow addRow = resDt.NewRow();
                    addRow["index"] = index + 1;
                    addRow["mat_id"] = matBean.mat_id;
                    addRow["mat_number"] = matBean.mat_number;
                    addRow["mat_name"] = matBean.mat_name;
                    addRow["mat_spe"] = matBean.mat_spe;
                    addRow["base_unit"] = matBean.base_unit;
                    addRow["create_orgid"] = matBean.create_orgid;
                    addRow["use_orgid"] = string.IsNullOrEmpty(matBean.use_ordid) ? "" : 
                                                matBean.use_ordid.Equals("100153") ? "BSW" : 
                                                matBean.use_ordid.Equals("1402597") ? "BSW(TH)" : "";
                    addRow["mat_group"] = matBean.mat_group;
                    addRow["doc_status"] = string.IsNullOrEmpty(matBean.doc_status) ? "" : 
                                                matBean.doc_status.Equals("A") ? "新建" : 
                                                matBean.doc_status.Equals("Z") ? "暂存" : 
                                                matBean.doc_status.Equals("B") ? "审核中" : 
                                                matBean.doc_status.Equals("C") ? "已审核" :
                                                matBean.doc_status.Equals("D") ? "重新审核" : "";
                    addRow["forbid_status"] = matBean.forbid_status;
                    addRow["board_qty"] = Math.Round(matBean.board_qty, 2);
                    addRow["data_status"] = "noChange";
                    resDt.Rows.Add(addRow);
                    index++;
                }
            }

            return resDt;
        }

        private MatInfo ChangeDataRowToBean(DataRow dr)
        {
            MatInfo resBean = null;
            int tmpInt = 0;
            decimal tmpDec = 0;

            if (dr != null)
            {
                resBean = new MatInfo 
                {
                    mat_id = dr["mat_id"] != DBNull.Value && int.TryParse(dr["mat_id"].ToString(),out tmpInt) ? tmpInt : 0,
                    mat_number = dr["mat_number"] != DBNull.Value ? dr["mat_number"].ToString() : "",
                    mat_name = dr["mat_name"] != DBNull.Value ? dr["mat_name"].ToString() : "",
                    mat_spe = dr["mat_spe"] != DBNull.Value ? dr["mat_spe"].ToString() : "",
                    base_unit = dr["base_unit"] != DBNull.Value ? dr["base_unit"].ToString() : "",
                    create_orgid = dr["create_orgid"] != DBNull.Value ? dr["create_orgid"].ToString() : "",
                    use_ordid = dr["use_orgid"] != DBNull.Value ? dr["use_orgid"].ToString() : "",
                    mat_group = dr["mat_group"] != DBNull.Value && int.TryParse(dr["mat_group"].ToString(), out tmpInt) ? tmpInt : 0,
                    doc_status = dr["doc_status"] == DBNull.Value ? "" :
                                    dr["doc_status"].ToString().Trim().Equals("新增") ? "A" :
                                    dr["doc_status"].ToString().Trim().Equals("暂存") ? "Z" :
                                    dr["doc_status"].ToString().Trim().Equals("审核中") ? "B" :
                                    dr["doc_status"].ToString().Trim().Equals("已审核") ? "C" :
                                    dr["doc_status"].ToString().Trim().Equals("重新审核") ? "D" : "",
                    forbid_status = dr["forbid_status"] != DBNull.Value ? dr["forbid_status"].ToString() : "",
                    board_qty = dr["board_qty"] != DBNull.Value && decimal.TryParse(dr["board_qty"].ToString(), out tmpDec) ? tmpDec : 0
                };
            }
            return resBean;
        }
        #endregion

        private void btnSave_Click(object sender, EventArgs e)
        {
            List<MatInfo> updateList = new List<MatInfo>();
            this.dgvMaterial.EndEdit();
            DataTable tmpDt = this.dgvMaterial.DataSource as DataTable;

            foreach (DataRow dr in tmpDt.Rows)
            {
                if (dr.RowState == DataRowState.Modified)
                {
                    updateList.Add(this.ChangeDataRowToBean(dr));
                }
            }

            if (updateList != null && updateList.Count > 0)
            {
                try
                {
                    int count = this._mat_ctrl.UpdateMatInfoForBean(updateList);
                    UIMessageBox.ShowSuccess("物料信息更新成功！");
                    this.btnSearch_Click(sender, e);
                }
                catch (Exception ex)
                {
                    UIMessageBox.ShowError("物料信息更新失败！" + "\r\n" + ex.Message);
                }
            }
        }
    }
}
